home *** CD-ROM | disk | FTP | other *** search
- Path: pegasus.montclair.edu!harmon
- From: harmon@pegasus.montclair.edu (Derek Harmon)
- Newsgroups: comp.lang.c
- Subject: Re: Question on argv
- Date: 1 Feb 1996 00:55:15 -0500
- Organization: Montclair State University
- Message-ID: <harmon.823153381@pegasus.montclair.edu>
- References: <4eoq3c$45j@usenet.ucs.indiana.edu>
- NNTP-Posting-Host: pegasus.montclair.edu
- X-Newsreader: NN version 6.5.0 #68 (NOV)
-
- ** Quoting a message from <gompa@nickel.ucs.indiana.edu> dated <31-Jan-1996>:
-
- > I am writing a program in which I want to
- > retrieve the arguments argv[1] ... argv[4].
- > argv[1] .. argv[3] are strings of characters.
- > I want to use argv[4] as an integer. Can
- > I do that?
-
- Strictly speaking, no. argv[4] is a pointer to characters. If you
- say argv[4] = 36, you are telling argv[4] to point to address 36. On
- many computers, this will go BOOM. On all others it will go ZOWIE. :)
-
- If you mean use argv[4] as a pointer to an integer, it is "messy"
- but in the sense C allows you the freedom to shoot yourself in the foot,
- it can be done.
-
- > how?
-
- Ok, here's a contrived example. Let's assume you have a program that
- takes 4 command-line arguments. The first will always be a string, the
- second will be an integer (no error-checking needed, really idealistic
- example here :) ). Note that the "integer" is going to be received as
- a string. This example will use atoi() to convert it to an integer, and
- then shoe-horn that integer back into argv[4]. It will then demonstrate
- how (for whatever reason) you can then use argv[4] as a pointer to an int.
-
- /* admittedly, these define macros work on 32-bit (2-byte) ints, and this */
- /* example presumes chars are 1-byte, which are ANSI no-no assumptions. */
- #define hiBYTE(x) (x & 65280)
- #define loBYTE(x) (x & 255)
-
- /* comment out if your machine is little endian (PC, etc) */
- #define BIG_ENDIAN 1
-
- /* main routine */
- int main(int argc, char *argv[])
- {
- int i;
-
- if (argc < 4) return( 0 ); /* didn't get the 4 arguments! */
-
- /* first, print out the three character string arguments */
- for (i=1; i < 4; i++) printf("argv[%d] = '%s'\n", i, argv[i]);
-
- i = atoi(argv[4]); /* convert integer in string to integer value, i */
-
- /* note, at smallest, argv[4] is 2-bytes, "A" is 'A' + '\0', or 65 00 */
- /* which is 65 in little endian, and a big number in big endian. */
-
- #ifdef BIG_ENDIAN
- argv[0] = hiBYTE(i);
- argv[1] = loBYTE(i);
- #else
- argv[0] = loBYTE(i);
- argv[1] = hiBYTE(i);
- #endif
-
- /* when printing, typecast argv[4] as a (int *). any reference to it */
- /* as a string hereafter will be erroneous and possibly (if < 10) fatal */
-
- printf("argv[4] = %d\n", (int *)argv[4]);
-
- return( 0 );
- }
-
- The only drawback to this is, if you are willing to go through all
- this trouble, why not just give it its' own int variable?? :D
-
- -- Stone
- --
- ... Adopt-A-PET
-
-
-